from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from apps.orders.models import Order
from apps.address.models import Address

@receiver(post_save, sender=Address)
def clear_address_cache(sender, instance, **kwargs):
    """清理地址缓存"""
    from django.core.cache import cache
    cache.delete(f'user_{instance.user_id}_default_address')

@receiver(post_delete, sender=Address)
def handle_deleted_address(sender, instance, **kwargs):
    """地址删除后的关联处理"""
    if instance.is_default:
        # 自动设置新的默认地址
        next_default = Address.objects.filter(
            user=instance.user
        ).exclude(id=instance.id).first()
        if next_default:
            next_default.is_default = True
            next_default.save()

@receiver(post_save, sender=Order)
def lock_used_address(sender, instance, **kwargs):
    """订单创建后锁定关联地址"""
    if instance.address_id:
        Address.objects.filter(id=instance.address_id).update(is_locked=True)